package com.jiukuaidao.zhulin.module.pay.wechat;

import com.jiukuaidao.library.net.MyRetroCallBack;
import com.jiukuaidao.zhulin.AppContext;
import com.jiukuaidao.zhulin.api.ApiConfirmPay;
import com.jiukuaidao.zhulin.data.TasksRepository;
import com.jiukuaidao.zhulin.module.pay.wechat.util.PayResult;
import com.jiukuaidao.zhulin.module.pay.wechat.util.WXKeys;
import com.tencent.mm.sdk.constants.Build;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

/**
 * Author : PaiTaSuo
 * Date : 2016/5/24
 * Description :
 */
public class WXPayPresenter implements WXPayContract.Presenter {
    private IWXAPI mApi;
    protected TasksRepository mRepository;
    protected WXPayContract.View mView;

    public WXPayPresenter(TasksRepository repository, WXPayContract.View view) {
        mRepository = repository;
        mView = view;
    }


    @Override
    public void pay(PayResult result) {
        PayReq req = new PayReq();
        req.appId = WXKeys.APP_ID;
        req.partnerId = result.partnerid;
        req.prepayId = result.prepayid;
        req.nonceStr = result.noncestr;
        req.timeStamp = result.timestamp;
        req.packageValue = result.package1;// "Sign=" + packageValue;
        req.sign = result.sign;
        mView.toast("正常调起支付");


        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
        mApi.sendReq(req);


    }

    @Override
    public void loadData() {
        mRepository.loadData(new ApiConfirmPay(mView.getOrderNumber(), new MyRetroCallBack<PayResult>() {
            @Override
            public void onSuccess(PayResult result, String errorCode, String msg) {
                mApi = WXAPIFactory.createWXAPI(AppContext.getContext(), WXKeys.APP_ID);
                mApi.registerApp(WXKeys.APP_ID);
                if (mApi.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT) {// 如果支持微信支付
                    pay(result);
                } else {// 不支持微信支付
                    mView.toast("不支持微信支付");
                }

            }

            @Override
            public void onFail(PayResult result, String errorCode, String msg) {
                mView.toast(msg);
            }

            @Override
            public void onError(Throwable t, int resCode, String msg) {
                mView.toast(msg);
            }
        }));

    }
}
